<template>
    <div class="menu-box">
        <div class="top-menu">
            <div class="left">
                <div class="logos">
                    <img src="@/assets/logo.png" alt="">
                    <span>启帆知识图谱平台</span>
                </div>
                <div class="silder-index">
                    <img src="@/assets/flod.png" @click="toggleCollapse" alt="">
                    <span>首页</span>
                </div>
            </div>
            <div class="right">
                <!-- <div class="silder-index">
                    <img src="@/assets/fullscreen.png" alt="">
                    <span>全屏显示</span>
                </div> -->
                <!-- <div class="lines"></div> -->
                <div class="user-box">
                    <div class="avatar-box">
                        <img :src="host + user.avatar" v-if="user.avatar" alt="">
                        <img src="@/assets/user.png" v-if="!user.avatar" alt="">
                    </div>
                    <div class="nickname-box" ref="userRef" v-click-outside="onClickUser">
                        <span>你好，</span>
                        <span>{{ name }}</span>
                        <el-icon><ArrowDownBold /></el-icon>
                    </div>
                </div>
                <el-popover ref="userpopoverRef" popper-class="notice-box" :virtual-ref="userRef" trigger="click" virtual-triggering width="150" popper-style="border-radius: 10px" placement="top-start">
                    <div class="user-div">
                        <div class="user-item" @click="userEdit">
                            <img src="@/assets/stuuser.png" alt="">
                            <span>个人信息</span>
                        </div>
                        <div class="user-item" @click="logout">
                            <img src="@/assets/logout.png" alt="">
                            <span>退出登录</span>
                        </div>
                    </div>
                </el-popover>
            </div>
        </div>
        <div class="left-menu" :style="{ maxWidth: menuStore.isCollapsed ? '70px' : '280px' }">
            <div class="menu-box" :style="{ width: menuStore.isCollapsed ? '70px' : '240px' }">
                <div class="menu-item" v-for="(item,index) in menuItems" :key="index" :class="{fold: menuStore.isCollapsed}">
                    <div class="parent" :class="{ active: menuStore.activeItem === index && item.child?.length > 0,borderradius: !menuStore.showChild[index], activenochild: menuStore.activeItem === index && (!item.child || item.child.length === 0) }" @click="menuClick(item, index)">
                        <div class="menus">
                            <img :src="menuStore.activeItem === index ? item.checkIcon : item.icon" alt="">
                            <span v-show="!menuStore.isCollapsed">{{ item.text }}</span>
                        </div>
                        <el-icon v-if="item.child?.length > 0" v-show="!menuStore.isCollapsed">
                            <ArrowDownBold v-if="menuStore.activeItem === index && menuStore.showChild[index]" />
                            <ArrowRightBold v-else />
                        </el-icon>
                    </div>
                    <div class="child" v-show="menuStore.activeItem === index && menuStore.showChild[index] && item.child?.length > 0" :class="menuStore.showChild[index] ? 'silderdown' : 'silderup'">
                        <div class="child-item" v-for="(child, keys) in item.child" :key="keys" @click.stop="childClick(child, keys)" :class="{ active: menuStore.activeChildIndex === keys }"> {{ child.text }} </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-dialog v-model="userDialogShow" width="50%" height="600px" top="15vh">
        <div class="user-edit-box">
            <el-upload class="avatar-uploader" :http-request="customUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" >
                <div class="avatar-box">
                    <span>更换头像</span>
                    <img :src="imageUrl" class="avatar" />
                </div>
            </el-upload>
            <div class="username">您好，{{ nickname }}</div>
            <div class="user-info">
                <div class="user-li">
                    <div class="label">老师账号：</div>
                    <el-input v-model="account" disabled />
                </div>
                <div class="user-li">
                    <div class="label">老师姓名：</div>
                    <el-input v-model="name" placeholder="请输入老师姓名" />
                </div>
            </div>
            <div class="user-info">
                <div class="user-li">
                    <div class="label">修改密码：</div>
                    <el-input v-model="pass" type="password" placeholder="请输入新密码" />
                </div>
                <div class="user-li">
                    <div class="label">确认密码：</div>
                    <el-input v-model="confirmPass" type="password" placeholder="请再次输入密码" />
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="userEdit"> 取消 </el-button>
                <el-button type="primary" @click="update"> 保存 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref, defineProps,defineEmits,unref,computed } from 'vue'
    import { ArrowDownBold, ArrowRightBold } from '@element-plus/icons-vue'
    import { useRouter } from 'vue-router';
    import { useMenuStore } from '@/stores/menu'
    import { ElMessageBox,ElMessage } from 'element-plus'
    import api from '@/api/index.js';

    const props = defineProps({ menuItems: { type: Array, required: true, default: () => [] }, })
    const emit = defineEmits(['update:isCollapsed'])
    const router = useRouter();
    const menuStore = useMenuStore()
    const menuItems = ref(props.menuItems);
    menuStore.initShowChild(menuItems.value);
    const userDialogShow = ref(false)
    const initialUser = JSON.parse(localStorage.getItem("user") || '{}');
    const user = ref(initialUser);
    const name = ref(initialUser.name || '');
    const account = ref(initialUser.username || '');
    const pass = ref('');
    const confirmPass = ref('');
    const updateImg = ref('')
    const host = ref("https://www.originxr.cn/");
    const imageUrl = computed(() => {
        if (user.value.avatar) {
            return user.value.avatar.startsWith('http') ? user.value.avatar : host.value + user.value.avatar;
        }
        return require("@/assets/user.png"); 
    });
    // 初始化用户数据
    const initUserData = () => {
        const userData = JSON.parse(localStorage.getItem("user") || '{}');
        user.value = userData;
        name.value = userData.name || '';
        account.value = userData.username || '';
    };
    // 更新本地用户缓存
    const updateUserCache = (newUserData) => {
        // 合并新旧数据
        const updatedUser = { ...user.value, ...newUserData };
        user.value = updatedUser;
        localStorage.setItem("user", JSON.stringify(updatedUser));
        window.dispatchEvent(new CustomEvent('userInfoUpdated', { 
            detail: { user: updatedUser } 
        }));
    };
    const toggleCollapse = () => {
        menuStore.toggleCollapse();
        emit('update:isCollapsed', menuStore.isCollapsed)
    }

    const menuClick = (item, index) => {
        if (menuStore.activeItem === index) {
            menuStore.toggleChild(index);
        } else {
            menuStore.resetChildren();
            if (item.child?.length > 0) {
                menuStore.toggleChild(index);
            }
        }
        menuStore.setActiveItem(index)
        if (!item.child || item.child.length === 0) {
            if(item.route) {
                router.push({ name: item.route.name });
            }
        }
    }

    const childClick = (child, childIndex) => {
        menuStore.setActiveChildIndex(childIndex)
        if(child.route) {
            router.push({ 
                name: child.route.name, 
            });
        }
    }
    const userEdit = () => {
        initUserData();
        userDialogShow.value = !userDialogShow.value
    }
    const userRef   = ref()
    const userpopoverRef = ref()
    const onClickUser = () => {
        unref(userpopoverRef).popperRef?.delayHide?.()
    }
    const logout = () => {
        ElMessageBox.confirm('是否确认退出登录？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'my-custom-message-box'
        }).then(() => {
            localStorage.removeItem("token");
            localStorage.removeItem("role");
            localStorage.removeItem("user");
            user.value = {}; // 清空用户对象
            name.value = ''; // 清空昵称
            account.value = ''; // 清空账号
            imageUrl.value = require("@/assets/user.png"); // 重置头像为默认
            router.push({ path: '/login' }); 
            ElMessage({ type: 'success', message: '已退出登录' });
        }).catch(() => {
            console.log("取消退出")
        });
    }
    const customUpload = (file) => {
        const formData = new FormData();
        formData.append("avatar", file.file);
        api.uploadAvatar(formData, {
            headers: { "Content-Type": "multipart/form-data" } 
        }).then(res => {
            if( res.code == 0 ){
                ElMessage({ type: 'success', message: '上传成功', })
                imageUrl.value = host.value + res.data
                updateImg.value = res.data
                updateUserCache({ avatar: res.data });
            } else {
                ElMessage({ type: 'error', message: '上传失败', })
            }
        }).catch(err => {
            console.error("上传失败:", err.response?.data || err.message);
        });
    }
    const beforeAvatarUpload = (file) => {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPGOrPNG) {
            ElMessage.error('头像只能是 JPG/PNG 格式!');
            return false;
        }
        if (!isLt2M) {
            ElMessage.error('头像大小不能超过 2MB!');
            return false;
        }
        return true;
    }
    const update = async () => {
        if (!name.value.trim()) {
            ElMessage({ type: 'warning', message: '请输入老师姓名' });
            return;
        }

        if (pass.value && pass.value !== confirmPass.value) {
            ElMessage({ type: 'warning', message: '两次输入的密码不一致' });
            return;
        }
        try {
            const params = { 
                name: name.value.trim(),
                id: user.value.id, 
                avatar: updateImg.value 
            }
            if (updateImg.value) {
                params.avatar = updateImg.value;
            }
            if (pass.value) {
                //更新密码
                const res = await api.passreset( { id:user.value.id,newPassword:pass.value } )
                console.log( res )
            }
            const res = await api.update(params)
            if (res.code === 0) {
                 const updatedData = {
                    name: name.value.trim(),
                    ...(updateImg.value && { avatar: updateImg.value })
                };
                updateUserCache(updatedData);
                userDialogShow.value = false
                ElMessage({ type: 'success', message: '更新成功' })
            } else {
                ElMessage.error('更新失败')
            }
        } catch (error) {
            ElMessage.error('网络错误，请重试')
        }
    }
    window.addEventListener('storage', (event) => {
        if (event.key === 'user') {
            const newUserData = JSON.parse(event.newValue || '{}');
            user.value = newUserData;
        }
    });
</script>

<style scoped>
    .menu-box .top-menu { background: #fff; height: 60px; width: 99%; display: flex; flex-direction: row; justify-content: space-between; margin: 0 auto; border-radius: 4px; }
    .menu-box .top-menu .left { display: flex; flex-direction: row; justify-content: space-around; }
    .menu-box .top-menu .left .logos { display: flex; flex-direction: row; justify-content: center; align-items: center; }
    .menu-box .top-menu .left .logos img { width: 25px; height: 25px; margin-left: 40px; cursor: pointer; }
    .menu-box .top-menu .left .logos span { margin-left: 10px; font-family: 微软雅黑, Microsoft YaHei, SimSun; cursor: pointer; font-size: 20px; font-weight: 500; }
    .menu-box .top-menu .left .silder-index { display: flex; flex-direction: row; justify-content: center; align-items: center; margin-left: 110px; }
    .menu-box .top-menu .left .silder-index img { width: 25px; height: 25px; cursor: pointer; }
    .menu-box .top-menu .left .silder-index span { margin-left: 10px; font-family: 微软雅黑, Microsoft YaHei, SimSun; }
    .menu-box .top-menu .right { display: flex; flex-direction: row; justify-content: space-around; margin-right: 40px; align-items: center; }
    .menu-box .top-menu .right .silder-index { display: flex; flex-direction: row; justify-content: center; align-items: center; margin-right: 30px; }
    .menu-box .top-menu .right .silder-index img { width: 25px; height: 25px; cursor: pointer; }
    .menu-box .top-menu .right .silder-index span { margin-left: 5px; font-family: 微软雅黑, Microsoft YaHei, SimSun; cursor: pointer; }
    .menu-box .top-menu .right .lines { height: 30px; width: 2px; background: #343B53; margin-right: 40px; }
    .menu-box .top-menu .right .user-box { display: flex; flex-direction: row; align-items: center; }
    .menu-box .top-menu .right .user-box .avatar-box { width: 40px; height: 40px; background: #D0D3DB; border-radius: 40px; display: flex; flex-direction: row; justify-content: center; align-items: end; }
    .menu-box .top-menu .right .user-box .avatar-box img { width: 40px; height: 40px; border-radius: 40px; }
    .menu-box .top-menu .right span { font-family: 微软雅黑, Microsoft YaHei, SimSun; cursor: pointer; }
    .menu-box .top-menu .right .nickname-box { display: flex; flex-direction: row; gap: 5px; align-items: center; }
    .menu-box .top-menu .right .nickname-box span { display: block; margin-left: 4px; }
    .left-menu { max-width: 280px; height: 100%; }
    .left-menu .menu-box { width: 240px; background: linear-gradient(135deg, #2E7CF4 0%, #0457D5 100%); margin-left: 40px; margin-top: 25px; border-radius: 10px; height: 85vh; display: flex; flex-direction: column; align-items: end; padding-top: 20px; }
    .menu-item { width: calc(90% - 20px); }
    .fold { transition: all 0.5s ease; width: 100%; }
    .fold img { margin-left: -5px; }
    .menu-item { will-change: transform, opacity; backface-visibility: hidden; display: flex; flex-direction: column; } 
    .menu-item .menus { margin-left: 15px; display: flex; flex-direction: row; align-items: center; position: relative; display: flex; align-items: center; white-space: nowrap; }
    .menu-item .menus span { margin-left: 10px; font-family: 微软雅黑, Microsoft YaHei, SimSun; font-size: 16px; color: #fff; }
    .menu-item img { width: 25px; height: 25px; margin: 0 auto; display: block; }
    .menu-item.active .menus span { color: #1D173E; }
    .left-menu, .menu-box { transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1); }
    .menu-item .menus span { transition: opacity 0.3s ease, transform 0.4s cubic-bezier(0.4, 0, 0.2, 1), width 0.4s ease; display: inline-block; min-width: 0; }
    .parent { padding: 15px 0 15px 0; display: flex; flex-direction: row; justify-content: space-between; cursor: pointer; align-items: center; margin-top: 20px; border-top-left-radius: 8px; padding-right: 20px; }
    .fold .parent { border-radius: 8px; width: 40px; justify-content: center; padding: 10px 0 10px 0; }
    .fold .menus { margin-left: 0; }
    .fold.menu-item { justify-content: center; align-items: center; }
    .parent.active { background: #fff; }
    .parent.activenochild { background: #fff; border-bottom-left-radius: 8px; }
    .parent.active .menus span { color: #000; }
    .parent.activenochild .menus span { color: #000; }
    .child { border-bottom-left-radius: 8px; background: #4D8DF0; }
    .child-item { width: 100%; padding: 15px 0 15px 0; color: #A2C3F6; cursor: pointer; }
    .child-item.active { color: #fff; }
    .silderdown { animation: scale-down-ver-top 0.3s cubic-bezier(0.390, 0.575, 0.565, 1.000) both; }
    .silderup { animation: scale-up-ver-top 0.3s cubic-bezier(0.390, 0.575, 0.565, 1.000) both; }
    @keyframes scale-down-ver-top { 0% { -webkit-transform: scaleY(0); transform: scaleY(0); -webkit-transform-origin: 100% 0%; transform-origin: 100% 0%; } 100% { -webkit-transform: scaleY(1); transform: scaleY(1); -webkit-transform-origin: 100% 0%; transform-origin: 100% 0%; } }
    @keyframes scale-up-ver-top { 0% { -webkit-transform: scaleY(1); transform: scaleY(1); -webkit-transform-origin: 100% 0%; transform-origin: 100% 0%; } 100% { -webkit-transform: scaleY(0); transform: scaleY(0); -webkit-transform-origin: 100% 0%; transform-origin: 100% 0%; } }
    .borderradius{border-bottom-left-radius: 10px;}

    .user-div{display: flex;flex-direction: column;justify-content: center;align-items: center;}
    .user-item{width: 90%;text-align: center;padding: 10px;border-bottom: 1px solid #dfdfdf;cursor: pointer;display: flex;flex-direction: row;justify-content: center;align-items: center;}
    .user-item:hover{background: #E6F5FE;}
    .user-item img{width: 20px;height: 20px;}
    .user-item span{margin-left: 5px;}
    .user-edit-box .avatar-box{position: relative;border-radius: 100px;width: 100px;height: 100px;overflow: hidden;}
    .user-edit-box .avatar{width: 100px;height: 100px;}
    .user-edit-box span{position: absolute;bottom: 0px;left: 0;width: 100px;text-align: center;background: rgb(0,0,0,0.5);color: #fff;font-family: 微软雅黑, Microsoft YaHei, SimSun;cursor: pointer;font-size: 12;padding-bottom: 5px;}
    .user-edit-box .username{width: 100%;font-family: 微软雅黑, Microsoft YaHei, SimSun;font-size: 16px;font-weight: 600;color: #000;margin-top: 10px;}
    .user-edit-box .user-info{display: flex;flex-direction: row;width: 60%;margin: 20px auto;gap: 10px;align-items: center;}
    .user-edit-box .user-info .label{line-height: 35px;font-family: 微软雅黑, Microsoft YaHei, SimSun;font-size: 14px;width: 120px;}
    .user-edit-box .user-info .user-li{display: flex;flex-direction: row;width: 100%;}
</style>